﻿using Utils.UIPermission;

namespace Pap.Web.Modules.Loan.Views
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.UI;

    using Coolite.Ext.Web;

    using Newtonsoft.Json.Linq;

    using Pap.Core.Utilities;
    using Pap.Data;
    using Pap.Web.Modules.Loan.ViewModel;
    using Pap.Web.Utils;

    /// <summary>
    /// 
    /// </summary>
    public partial class AssociationBankDeposite : BasePage<AssociationBankDepositeViewModel>, IPermittedPage
    {
        #region [ Properties ]

        /// <summary>
        /// Gets the bank accountdeposit ID.
        /// </summary>
        private string BankAccountdepositID
        {
            get { return Request.QueryString["bankAccountdepositID"]; }
        }

        /// <summary>
        /// Gets or sets the deposite receipts.
        /// </summary>
        /// <value>
        /// The deposite receipts.
        /// </value>
        private List<IReceipt> DepositeReceipts
        {
            get
            {
                return Session["DepositeReceipts"] as List<IReceipt>;
            }
            set
            {
                Session["DepositeReceipts"] = value;
            }
        }

        /// <summary>
        /// Gets or sets the paid receipts.
        /// </summary>
        /// <value>
        /// The paid receipts.
        /// </value>
        private List<IReceipt> PaidReceipts
        {
            get
            {
                return Session["PaidReceipts"] as List<IReceipt>;
            }
            set
            {
                Session["PaidReceipts"] = value;
            }
        }

        #endregion

        #region [ Events ]
        /// <summary>
        /// Handles the Clicked event of the BtnBack control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void BtnBack_Clicked(object sender, AjaxEventArgs e)
        {
            this.RedirectToPreviousPage();
        }

        /// <summary>
        /// Handles the Clicked event of the BtnDeposit control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void BtnDeposit_Clicked(object sender, AjaxEventArgs e)
        {
            if (e.ExtraParams["gridDepositReceipts"] != null)
            {
                string jsonString = e.ExtraParams["gridDepositReceipts"].ToString();
                JArray jsonArray = JSON.Deserialize(jsonString) as JArray;

                if (jsonArray.Count > 0)
                {
                    var depositeReceiptsIDs = from item in jsonArray
                                              where item["ReceiptID"] != null
                                              select new Guid(item["ReceiptID"].ToString().Trim('"'));

                    this.ViewModel.AssociationDeposit(txtApplicationNumber.Text, cmbProjects.SelectedItem.Value.ToGuid(),
                                                      InsertAttchments1.GetInsertedIDs(), depositeReceiptsIDs,
                                                      txtNotes.Text,
                                                      double.Parse(this.txtdepositTotalAmount.Text));

                    txtBalanceBeforeDeposit.Text = this.ViewModel.GetAssociationBalance(cmbProjects.SelectedItem.Value.ToGuid()).ToString();
                    PaidReceipts = this.ViewModel.GetPaidReceipts(
                    cmbProjects.SelectedItem.Value.ToGuid(), RegistryInfo.CommitteeID).ToList();
                    RefreshGridsData();
                    txtdepositTotalAmount.Text = (0).ToString();
                    this.RedirectToPreviousPage();

                }
                else
                {
                    Ext.Msg.Show(
                        new MessageBox.Config
                        {
                            Title = GetLocalResourceObject("ErrorMSG").ToString(),
                            Message = GetLocalResourceObject("ErrorTitle").ToString(),
                            Icon = MessageBox.Icon.ERROR
                        });
                }
            }
        }

        /// <summary>
        /// Handles the Selected event of the CmbProjects control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void CmbProjects_Selected(object sender, AjaxEventArgs e)
        {
            PaidReceipts = this.ViewModel.GetPaidReceipts(
                cmbProjects.SelectedItem.Value.ToGuid(), RegistryInfo.CommitteeID).ToList();

            txtBalanceBeforeDeposit.Text = this.ViewModel.GetAssociationBalance(
                cmbProjects.SelectedItem.Value.ToGuid()).ToString();

            RefreshGridsData();
        }

        /// <summary>
        /// Handles the Command event of the GridDepositReceipts control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void GridDepositReceipts_Command(object sender, AjaxEventArgs e)
        {
            if (e.ExtraParams["CommandName"] != null)
            {
                if (e.ExtraParams["CommandName"].Equals("DeleteReceipt"))
                {
                    Guid receiptID = e.ExtraParams["ReceiptID"].ToGuid();
                    var tempReciept = DepositeReceipts.Single(rec => rec.ReceiptID == receiptID);
                    PaidReceipts.Add(tempReciept);
                    DepositeReceipts = DepositeReceipts.Where(receipt => receipt.ReceiptID != receiptID).ToList();
                    RefreshGridsData();

                    var tempTotal = (Convert.ToDouble(txtdepositTotalAmount.Text) - tempReciept.ReceiptAmount);

                    if (tempTotal > 0)
                        txtdepositTotalAmount.Text = tempTotal.ToString();
                    else
                        txtdepositTotalAmount.Text = string.Empty;
                }
            }
        }

        /// <summary>
        /// Handles the Command event of the GridPaidReciepts control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void GridPaidReciepts_Command(object sender, AjaxEventArgs e)
        {
            if (e.ExtraParams["CommandName"] != null)
            {
                if (e.ExtraParams["CommandName"].Equals("AddReceipt"))
                {
                    Guid receiptID = e.ExtraParams["ReceiptID"].ToGuid();
                    IReceipt tempReciept = PaidReceipts.Single(rec => rec.ReceiptID == receiptID);
                    DepositeReceipts.Add(tempReciept);
                    PaidReceipts = PaidReceipts.Where(receipt => receipt.ReceiptID != receiptID).ToList();
                    RefreshGridsData();
                    if (!txtdepositTotalAmount.Text.IsNullOrEmpty())
                        txtdepositTotalAmount.Text = (Convert.ToDouble(txtdepositTotalAmount.Text) + tempReciept.ReceiptAmount).ToString();
                    else
                        txtdepositTotalAmount.Text = tempReciept.ReceiptAmount.ToString();
                }
            }
        }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack && !Ext.IsAjaxRequest)
            {
                PaidReceipts = new List<IReceipt>();
                DepositeReceipts = new List<IReceipt>();
                if (!BankAccountdepositID.IsNullOrEmpty())
                {
                    FillDepositData(BankAccountdepositID.ToGuid());
                }
                storeProjects.DataSource = this.ViewModel.GetUserProjects();
                storeProjects.DataBind();

                txtAssociationName.Text = this.ViewModel.GetAssociationName();
            }
        }

        #endregion

        #region [ Methods ]

        /// <summary>
        /// Fills the deposit data.
        /// </summary>
        /// <param name="bankAccountDepoID">The bank account depo ID.</param>
        private void FillDepositData(Guid bankAccountDepoID)
        {
            var associationDeposit = this.ViewModel.GetAssociationDeposit(bankAccountDepoID);
            cmbProjects.SelectedItem.Value = associationDeposit.CommitteeBankAccount.ProjectID.ToString();
            dateDepositeDate.Value = associationDeposit.DepositDate;
            txtApplicationNumber.Text = associationDeposit.OperationNumber;
            txtNotes.Text = associationDeposit.Notes;
            var receipts = associationDeposit.CommitteeBankAccountDepositReceipts.Select(
                rec => rec.Receipt);
            var depositAmount = receipts.Select(rec => rec.ReceiptAmount).Sum();
            txtdepositTotalAmount.Text = depositAmount.ToString();
            DepositeReceipts = receipts.ToList();
            RefreshGridsData();

            txtBalanceBeforeDeposit.Text = (associationDeposit.CommitteeBankAccount.Balance - depositAmount).ToString();

            // Commented by mina Alphonce, duuno what this line do
            //InsertAttchments1.ViewMode = InsertAttchments.AttachemntsViewMode.Display;
            InsertAttchments1.SetImages(associationDeposit.CommitteeBankAccountDepositAttachments.Select(att => att.Image));

            btnDeposit.Disabled = true;
            gridDepositReceipts.Disabled = true;
            txtApplicationNumber.Disabled = true;
            cmbProjects.Disabled = true;
            dateDepositeDate.Disabled = true;
            txtNotes.Disabled = true;
        }

        /// <summary>
        /// Refreshes the grids data.
        /// </summary>
        private void RefreshGridsData()
        {
            storePaidReciepts.DataSource = from receipt in PaidReceipts
                                           select new
                                           {
                                               ReceiptNumber = receipt.ReceiptNumber,
                                               ReceiptType = receipt.ReceiptTypeObj.Name,
                                               ReceiptDate = receipt.ReceiptDate,
                                               ReceiptAmount = receipt.ReceiptAmount,
                                               ReceiptID = receipt.ReceiptID
                                           };
            storePaidReciepts.DataBind();

            storeDepositReciepts.DataSource = from receipt in DepositeReceipts
                                              select new
                                              {
                                                  ReceiptNumber = receipt.ReceiptNumber,
                                                  ReceiptType = receipt.ReceiptTypeObj.Name,
                                                  ReceiptDate = receipt.ReceiptDate,
                                                  ReceiptAmount = receipt.ReceiptAmount,
                                                  ReceiptID = receipt.ReceiptID
                                              };
            storeDepositReciepts.DataBind();
        }

        #endregion

        public string PermissionName
        {
            get { return Permissions.AssociationBankDeposite.ToString(); }
        }
    }
}